<template>
  <div class="flight-query-panel">
    <div class="panel-content" v-if="activeTab === 'flight'">
      <div class="query-section">
        <!-- 飞行轨迹筛选 -->
        <div class="section-title flight-path-title">
          <div class="section-label">飞行轨迹：</div>
          <div class="checkbox-group">
            <el-checkbox-group v-model="queryParams.sources" @change="historicalFlightData"
              class="custom-checkbox-group">
              <el-checkbox v-for="item in aircraftType" :key="item" :label="item.label" :value="item.value"
                class="custom-checkbox"></el-checkbox>
            </el-checkbox-group>
          </div>
        </div>

        <!-- 飞机编号筛选 -->
        <div class="section-title aircraft-code-title">
          <div class="section-label">飞机编号：</div>
          <div class="filter-action">
            <div class="selected-codes" @click="openCodeSelector">
              <span v-if="selectedCodes.length === 0">全部</span>
              <span v-else>{{ selectedCodesText }}</span>
              <el-icon class="filter-icon">
                <Filter />
              </el-icon>
            </div>
            <!-- <div class="selection-counts" v-if="selectedCodes.length > 0">
              已选择 <span>{{ selectedCodes.length }}</span> / {{ aircraftCodes.length }}
            </div> -->
          </div>
        </div>

        <div class="section-title aircraft-code-title">
          <div class="section-label">飞机日期：</div>
          <div class="filter-action">
            <el-date-picker v-model="queryParams.date" type="date" value-format="YYYY-MM-DD" format="YYYY-MM-DD"
              placeholder="请选择日期" @change="historicalFlightData" />
          </div>
        </div>

        <!-- 架次列表标题 -->
        <div class="section-title flight-list-title">
          <div class="section-label">架次列表：</div>
        </div>
      </div>

      <!-- 架次列表内容 -->
      <div class="flight-list-container">
        <div v-if="flightList.length > 0" class="flights-wrapper">
          <div v-for="(flight, index) in flightList" :key="index" class="flight-item" :class="{
            selected: selectedFlights.includes(flight.order),
            located: locatedFlight === flight.order,
          }" @click="toggleFlightSelection(flight)">
            <div class="flight-info">
              <div class="flight-name">{{ flight.order }}</div>
              <div class="flight-meta">
                <span class="flight-time">{{ flight.startsAt }}</span>
                <span class="flight-code">{{ flight.airplane }}</span>
              </div>
            </div>
            <div class="flight-actions">
              <el-tooltip content="架次详情" placement="top" :show-after="300">
                <el-button size="small" type="primary" circle @click.stop="openDmtDrawer(flight)">
                  <el-icon>
                    <WarningFilled />
                  </el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="定位飞机" placement="top" :show-after="300">
                <el-button size="small" type="success" circle :class="{ 'located-btn': locatedFlight === flight.order }"
                  @click.stop="locateFlight(flight.order)">
                  <el-icon>
                    <LocationInformation />
                  </el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </div>
        </div>

        <!-- 架次列表空状态 -->
        <div v-else class="empty-state">
          <img src="@/assets/images/empty-data.png" alt="暂无数据" class="empty-icon" />
          <p class="mt10px">暂无架次</p>
        </div>
      </div>
    </div>
    <!-- 飞机编号选择器弹窗 -->
    <el-dialog title="飞机编号选择" v-model="codeDialogVisible" width="500px" :modal="true" :append-to-body="true"
      :close-on-click-modal="false" destroy-on-close class="code-selector-dialog">
      <div class="code-selector">
        <div class="code-manage">
          <el-checkbox v-model="selectAllCodes" label="全选" class="code-checkbox">
          </el-checkbox>
          <el-input v-model="codeSearchText" placeholder="搜索编号" class="code-search" prefix-icon="Search"
            clearable></el-input>
        </div>

        <div class="code-list">
          <el-checkbox-group v-model="queryParams.airplanes" class="code-checkbox-group">
            <div v-for="(code, index) in filteredAircraftCodes" :key="index" class="code-item">
              <el-checkbox :label="code.label" :value="code.value" class="code-checkbox">
              </el-checkbox>
            </div>
          </el-checkbox-group>

          <!-- 空状态 -->
          <div v-if="filteredAircraftCodes.length === 0" class="empty-search">
            <el-icon>
              <Search />
            </el-icon>
            <p>未找到匹配的编号</p>
          </div>
        </div>

        <div class="selection-summary">
          已选择 <span>{{ queryParams.airplanes.length }}</span> /
          {{ aircraftCodes.length }} 个编号
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelCodeSelection">取消</el-button>
          <el-button type="primary" @click="confirmCodeSelection">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  computed,
  watch,
  onMounted,
  onBeforeUnmount,
  inject,
} from "vue";
import {
  filterAddOrModify,
  // removeMarker,
  // toggleTrailVisibility,
  // updateTrailStyle,
  // toggleCameraTracking,
  getMap,
} from "@/mapbox/main/index.js";
import resData from "./data.json";
import {
  ArrowRight,
  View,
  Edit,
  Delete,
  Plus,
  Filter,
  Search,
  Aim,
  LocationInformation,
} from "@element-plus/icons-vue";
import {
  getDictList,
  historicalFlights,
  historicalTrajectory,
} from "@/api/aircraft";
import { ElMessage } from "element-plus";
import timeAxisStore from "@/stores/modules/timeAxis";
import drawerStore from "@/stores/modules/drawer";
import useInfoDataStore from "@/stores/modules/infoData";
import { MultiAircraftReplayController } from "@/mapbox/mapbox_core/playback/index";

const infoData = useInfoDataStore();
const timeAxis = timeAxisStore()
const drawer = drawerStore()

// 定义事件
const emit = defineEmits(["select-flight", "show-drawer", "loading-change"]);

// 当前激活的标签页
const activeTab = ref("flight");

// 定位飞机相关
const locatedFlight = ref(null);

// 查询参数
const queryParams = ref({
  sources: [],
  airplanes: [],
  date: new Date().toISOString().split("T")[0],
});

// 飞机编号数据
const aircraftCodes = ref([]);
// 飞机轨迹类型
const aircraftType = ref([]);

// 选中的编号
const selectedCodes = ref([]);
const tempSelectedCodes = ref([]);
const codeSearchText = ref("");

// 编号选择器弹窗
const codeDialogVisible = ref(false);


// 轨迹加载状态
const isTrajectoryLoading = ref(false);

const timeAxisRef = inject('timeAxisRef', null);

// 获取字典数据
const getDictListData = async () => {
  try {
    const res = await getDictList();
    aircraftCodes.value = res.find((item) => item.type === "AIRPLANE").elements;
    aircraftType.value = res.find((item) => item.type === "SOURCE").elements;
    queryParams.value.sources = aircraftType.value.map((item) => item.value);
    queryParams.value.airplanes = aircraftCodes.value.map((item) => item.value);
    infoData.dictionaries = res
    historicalFlightData();
  } catch (error) {
    console.error(error);
  }
};

// 获取实时架次数据
const historicalFlightData = async () => {
  try {
    // 清除之前选中的航班和轨迹数据
    selectedFlights.value = [];
    timeAxis.clearTimeAxis();

    const res = await historicalFlights(queryParams.value);
    flightList.value = res;
  } catch (error) {
    console.error(error);
  }
};


// 解析飞行数据
const parseData = (dataString) => {
  const fields = [
    "flightNumber",
    "dataSource",
    "timeStamp",
    "longitude",
    "latitude",
    "altitude",
    "groundSpeed",
    "course",
    "temperature",
    "humidity",
    "airPressure",
    "windSpeed",
    "windDirection",
    "typesAndDosagesOfCatalysts",
    "currentNumberOfFlares",
    "numberOfLeftFlameBullets",
    "numberOfRightFlameBullets",
    "flameState",
    "trueAirspeed",
    "model",
  ];

  const values = dataString.split(",");
  const dataObject = {};

  for (let i = 0; i < fields.length; i++) {
    dataObject[fields[i]] = values[i] !== "null" ? values[i] : null;
  }
  dataObject["id"] = dataObject["flightNumber"];
  return dataObject;
};

// 获取轨迹数据
const getWithTrajectory = async (id, province) => {
  try {
    if (timeAxis.timeList.find(item => item.id == id)) {
      timeAxis.timeList = timeAxis.timeList.filter(item => item.id != id);
      return;
    }

    isTrajectoryLoading.value = true;
    emit("loading-change", true);

    // 设置加载超时处理
    const loadingTimeout = setTimeout(() => {
      if (isTrajectoryLoading.value) {
        isTrajectoryLoading.value = false;
        emit("loading-change", false);
        ElMessage.warning("轨迹数据加载超时，请稍后再试");
      }
    }, 15000); // 15秒超时

    try {
      // 获取历史轨迹数据
      const response = await historicalTrajectory(id);

      // 清除超时定时器
      clearTimeout(loadingTimeout);

      if (response && response.length > 0) {
        const allDataPoints = response.map((item) => parseData(item));

        let historyList = allDataPoints.map((i) => {
          return {
            position: [Number(i.longitude), Number(i.latitude)],
            timestamp: i.timeStamp,
            properties: i,
          };
        });

        // 添加新的轨迹数据
        timeAxis.addTimeData({
          id,
          data: historyList,
          timestamp: historyList[0]?.timestamp
        });

        timeAxis.controller.addAircraft(id, historyList);
        
        timeAxis.setTime({
          startTime: timeAxis.controller.getEarliestStartTime(),
          endTime: timeAxis.controller.getLatestEndTime(),
        });
        infoData.setHistoryData(allDataPoints);
      }

      // 关闭加载状态
      isTrajectoryLoading.value = false;
      emit("loading-change", false);
    } catch (error) {
      // 清除超时定时器
      clearTimeout(loadingTimeout);

      console.error("获取历史轨迹数据失败:", error);
      isTrajectoryLoading.value = false;
      emit("loading-change", false);
      ElMessage.error("获取历史轨迹数据失败");
    }
  } catch (error) {
    isTrajectoryLoading.value = false;
    emit("loading-change", false);
    console.error("获取轨迹数据失败:", error);
    ElMessage.error("获取轨迹数据失败");
  }
};

onMounted(() => {
  getDictListData();
  timeAxis.controller = new MultiAircraftReplayController({
    defaultSpeed: timeAxis.timeIntervalValue,
    cleanupInterval: 2000,
    showFullTrail: true,
    trailColor: "#ff0000",
    trailWidth: 3,
  });

  timeAxis.controller.init(getMap());
  timeAxis.controller.removeAllAircraft()
});

onBeforeUnmount(() => {
  timeAxis.timeList = [];
});



// 筛选后的编号列表
const filteredAircraftCodes = computed(() => {
  if (!codeSearchText.value) return aircraftCodes.value;
  return aircraftCodes.value.filter(
    (item) =>
      item.label.toLowerCase().includes(codeSearchText.value.toLowerCase()) ||
      (item.remark &&
        item.remark.toLowerCase().includes(codeSearchText.value.toLowerCase()))
  );
});

// 选中的编号文本（逗号分隔）
const selectedCodesText = computed(() => {
  if (selectedCodes.value.length === 0) return "全部";
  if (selectedCodes.value.length === aircraftCodes.value.length) return "全部";
  const selectedLabels = selectedCodes.value.map((value) => {
    const foundItem = aircraftCodes.value.find((item) => item.value === value);
    return foundItem ? foundItem.label : value;
  });

  return selectedLabels.join("，");
});

// 飞机架次
const flightList = ref([]);
// 选中的航班
const selectedFlights = ref([]);

const selectAllCodes = computed({
  get() {
    return queryParams.value.airplanes.length === aircraftCodes.value.length;
  },
  set(val) {
    if (val) {
      queryParams.value.airplanes = aircraftCodes.value.map(
        (item) => item.value
      );
    } else {
      queryParams.value.airplanes = [];
    }
  },
});

// 打开编号选择器
const openCodeSelector = () => {
  tempSelectedCodes.value = [...selectedCodes.value];
  queryParams.value.airplanes = [...selectedCodes.value];

  if (
    selectedCodes.value.length === 0 ||
    selectedCodes.value.length === aircraftCodes.value.length
  ) {
    queryParams.value.airplanes = aircraftCodes.value.map((item) => item.value);
  }

  codeSearchText.value = "";
  codeDialogVisible.value = true;
};

// 取消编号选择
const cancelCodeSelection = () => {
  selectedCodes.value = [...tempSelectedCodes.value];
  codeDialogVisible.value = false;
};

// 确认编号选择
const confirmCodeSelection = () => {
  selectedCodes.value = [...queryParams.value.airplanes];

  if (
    selectedCodes.value.length === 0 ||
    selectedCodes.value.length === aircraftCodes.value.length
  ) {
    selectedCodes.value = [];
  }

  codeDialogVisible.value = false;
  historicalFlightData();
};

// 切换架次选择
const toggleFlightSelection = (data) => {
  let id = data.order
  const index = selectedFlights.value.indexOf(id);

  if (index > -1) {
    selectedFlights.value.splice(index, 1);

    if (locatedFlight.value === id) {
      locatedFlight.value = null;
    }

    if (timeAxisRef && typeof timeAxisRef.value.removeAircraftTrail === 'function') {
      timeAxisRef.value.removeAircraftTrail(id);
    }
  } else {
    selectedFlights.value.push(id);
    getWithTrajectory(id, data.airplane);
  }
};


// 打开飞行参数数据抽屉
const openDmtDrawer = (flight) => {
  if (
    !Array.isArray(selectedFlights.value) ||
    !selectedFlights.value.includes(flight.order)
  ) {
    ElMessage.warning("请先选择该架次，才能查看DMT数据");
    return;
  }

  emit("show-drawer");
};

// 处理定位飞机
const locateFlight = (flightId) => {
  locatedFlight.value = locatedFlight.value === flightId ? null : flightId;

  // if (locatedFlight.value) {
  //   // 查找选中的航班数据
  //   const flight = flightList.value.find((item) => item.order === flightId);
  //   if (flight) {
  //     // 获取该架次的历史数据
  //     const flightData = eventSources.value[flightId];
  //     let longitude = null;
  //     let latitude = null;

  //     // 如果有历史数据，使用最新点的经纬度
  //     if (
  //       flightData &&
  //       flightData._allHistoryData &&
  //       flightData._allHistoryData.length > 0
  //     ) {
  //       const lastPoint =
  //         flightData._allHistoryData[flightData._allHistoryData.length - 1];
  //       longitude = lastPoint.longitude ? Number(lastPoint.longitude) : null;
  //       latitude = lastPoint.latitude ? Number(lastPoint.latitude) : null;
  //     }

  //     // 发送select-flight事件，传递选中的航班数据
  //     emit("select-flight", {
  //       flightNo: flight.order,
  //       date: queryParams.value.date,
  //       takeoffTime: flight.startsAt,
  //       airplane: flight.airplane,
  //       longitude: longitude,
  //       latitude: latitude,
  //     });

  //     // 在地图上定位到该航班
  //     const map = getMap();
  //     if (map) {
  //       console.log("定位到历史航班:", flight, "坐标:", longitude, latitude);
  //     }
  //   }
  // }
};
</script>

<style lang="scss" scoped>
.flight-query-panel {
  width: 100%;
  max-height: 84vh;

  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  overflow: auto;

  .panel-content {
    flex: 1;
    padding: 12px;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .query-section {
      flex-shrink: 0;
      padding-right: 5px;

      .section-title {
        display: flex;
        align-items: center;
        margin-bottom: 10px;
        padding-bottom: 8px;
        font-size: 14px;
        color: #303133;
        border-bottom: 1px solid #ebeef5;

        .section-label {
          min-width: 70px;
          font-weight: 500;
          color: #333;
        }

        .checkbox-group {
          flex: 1;
          overflow: auto;

          .custom-checkbox-group {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;

            .custom-checkbox {
              margin-right: 0 !important;
              border-radius: 4px;
              padding: 2px;
              box-sizing: border-box;

              :deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
                color: #409eff;
              }

              :deep(.el-checkbox__label) {
                font-size: 12px;
                padding-left: 6px;
              }

              :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
                background-color: #409eff;
                border-color: #409eff;
              }
            }
          }
        }

        &.flight-path-title {
          margin-bottom: 10px;
        }

        &.aircraft-code-title {
          margin-bottom: 10px;

          .filter-action {
            flex: 1;

            .selected-codes {
              display: inline-flex;
              align-items: center;
              color: #409eff;
              cursor: pointer;
              font-size: 13px;
              background-color: #f0f7ff;
              padding: 4px 10px;
              border-radius: 4px;
              max-width: 200px;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
              transition: all 0.2s;
              border: 1px solid #e0efff;

              &:hover {
                background-color: #e0efff;
                border-color: #c6e2ff;
              }

              .filter-icon {
                margin-left: 6px;
                font-size: 12px;
              }
            }

            .selection-counts {
              margin-top: 4px;
              margin-left: 2px;
              font-size: 12px;
              color: #606266;

              span {
                color: #409eff;
                font-weight: 500;
              }
            }
          }
        }

        &.flight-list-title {
          display: flex;
          justify-content: space-between;
          align-items: center;
          border-bottom: none;
          margin-bottom: 6px;
          padding-bottom: 0;

          .add-flight-btn {
            font-size: 12px;
            padding: 4px 8px;
            height: 28px;

            .el-icon {
              margin-right: 2px;
            }
          }
        }
      }
    }

    .flight-list-container {
      flex: 1;
      overflow-y: auto;
      margin-top: 0;
      padding: 5px;
      background-color: #fff;

      &::-webkit-scrollbar {
        width: 4px;
      }

      &::-webkit-scrollbar-thumb {
        background-color: #d0d7de;
        border-radius: 10px;
      }

      &::-webkit-scrollbar-track {
        background-color: transparent;
      }

      .flights-wrapper {
        height: 100%;
      }

      .flight-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 10px;
        border-radius: 4px;
        border: 1px solid #edf2fc;
        margin-bottom: 6px;
        cursor: pointer;
        transition: all 0.2s;
        background-color: #fff;

        &:hover {
          background-color: #f5f9ff;
          border-color: #d9e8ff;
        }

        &.selected {
          background-color: #ecf5ff;
          border-color: #b3d8ff;
        }

        &.located {
          background-color: #f0f0f0;
          border-color: #d0d0d0;
        }

        .flight-info {
          .flight-name {
            font-weight: 500;
            font-size: 14px;
            margin-bottom: 4px;
            color: #303133;
          }

          .flight-meta {
            font-size: 12px;
            color: #909399;
            display: flex;
            gap: 8px;

            .flight-time {
              color: #606266;
            }

            .flight-code {
              color: #67c23a;
              font-weight: 500;
            }
          }
        }

        .flight-actions {
          display: flex;
          gap: 4px;

          .el-button {
            padding: 5px;
            font-size: 12px;
          }
        }
      }

      // 空状态样式
      .empty-state {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 20px 0;
        box-sizing: border-box;

        .empty-icon {
          width: 130px;
          opacity: 0.7;
        }

        p {
          color: #909399;
          font-size: 13px;
          margin-bottom: 12px;
        }

        .el-button {
          padding: 6px 12px;
          font-size: 12px;
        }
      }
    }
  }
}

// 编号选择器样式
.code-selector-dialog {
  :deep(.el-dialog__header) {
    padding: 15px;
    border-bottom: 1px solid #ebeef5;
    margin-right: 0;

    .el-dialog__title {
      font-size: 16px;
      font-weight: 500;
      color: #303133;
    }
  }

  :deep(.el-dialog__body) {
    padding: 15px;
  }

  :deep(.el-dialog__footer) {
    padding: 10px 15px;
    border-top: 1px solid #ebeef5;
  }
}

.code-selector {
  .code-manage {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;

    .code-search {
      width: 180px;
    }
  }

  .code-list {
    height: 300px;
    overflow-y: auto;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    background-color: #fff;
    margin-bottom: 10px;

    &::-webkit-scrollbar {
      width: 4px;
    }

    &::-webkit-scrollbar-thumb {
      background-color: #dcdfe6;
      border-radius: 10px;
    }

    &::-webkit-scrollbar-track {
      background-color: #f5f7fa;
    }

    .code-checkbox-group {
      display: flex;
      flex-direction: column;
      width: 100%;
      padding: 5px 0;

      .code-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 6px 10px;
        transition: all 0.2s;
        border-bottom: 1px solid #f5f7fa;

        &:hover {
          background-color: #f7f9fc;
        }

        &:last-child {
          border-bottom: none;
        }

        .code-checkbox {
          width: 100%;
          font-size: 13px;
          display: flex;
          align-items: center;

          :deep(.el-checkbox__label) {
            display: flex;
            justify-content: space-between;
            width: 100%;
            padding-left: 8px;
          }

          .code-value {
            font-weight: 500;
            color: #303133;
          }

          .code-remark {
            color: #909399;
            font-size: 12px;
            margin-left: 8px;
          }
        }
      }
    }

    // 搜索为空状态
    .empty-search {
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 20px 0;
      color: #909399;

      .el-icon {
        font-size: 24px;
        margin-bottom: 8px;
        opacity: 0.5;
      }

      p {
        font-size: 13px;
      }
    }
  }

  .selection-summary {
    text-align: right;
    font-size: 12px;
    color: #606266;
    margin-bottom: 0;

    span {
      color: #409eff;
      font-weight: 500;
    }
  }
}
</style>
